package com.hzz.openglstudy.render

import android.content.Context
import android.opengl.GLES20.*
import android.opengl.GLSurfaceView
import com.hzz.openglstudy.R
import com.hzz.openglstudy.util.compileFragmentShader
import com.hzz.openglstudy.util.compileVertexShader
import com.hzz.openglstudy.util.linkProgram
import com.hzz.openglstudy.util.readFileFromResource
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 * Created by hzz on 2018/6/13.
 */
class N3AirHockeyRender(private val context: Context) : GLSurfaceView.Renderer {
    companion object {
        const val POSITION_COMPONENT_COUNT = 2
        const val COLOR_COMPONENT_COUNT=3
        const val BYTES_PER_FLOAT = 4

        const val STRIDE= (POSITION_COMPONENT_COUNT+ COLOR_COMPONENT_COUNT)* BYTES_PER_FLOAT

        const val A_POSITION = "a_Position"
        const val A_COLOR="a_Color"
    }

    private var vertexData: FloatBuffer
    private var aPositionLocation = 0
    private var aColorLocation=0

    init {
        val tableVertices = floatArrayOf(
                //Triangle Fan
                0f, 0f,1f,1f,1f,
                -0.5f, -0.5f,0.7f,0.7f,0.7f,
                0.5f, -0.5f,0.7f,0.7f,0.7f,
                0.5f, 0.5f,0.7f,0.7f,0.7f,
                -0.5f, 0.5f,0.7f,0.7f,0.7f,
                -0.5f, -0.5f,0.7f,0.7f,0.7f,

                //line 1
                -0.5f, 0f,1f,0f,0f,
                0.5f, 0f,1f,0f,0f,
                //Mallets
                0f, -0.25f,0f,0f,1f,
                0f, 0.25f,1f,0f,0f
        )

        vertexData = ByteBuffer.allocateDirect(tableVertices.size * BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer()
        vertexData.put(tableVertices)
    }

    override fun onDrawFrame(gl: GL10?) {
        glClear(GL_COLOR_BUFFER_BIT)

        glDrawArrays(GL_TRIANGLE_FAN,0,6)

    }


    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        glViewport(0, 0, width, height)
    }

    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        glClearColor(0.0f, 0.0f, 0.0f, 0f)

        val vertexShaderCode = context.readFileFromResource(R.raw.simple_n3_vertex_shader)
        val fragmentShaderCode = context.readFileFromResource(R.raw.simple_n3_fragment_shader)

        val vertexShader = compileVertexShader(vertexShaderCode)
        val fragmentShader = compileFragmentShader(fragmentShaderCode)

        val program = linkProgram(vertexShader, fragmentShader)
        glUseProgram(program)

        aPositionLocation= glGetAttribLocation(program, A_POSITION)
        aColorLocation= glGetAttribLocation(program, A_COLOR)

        vertexData.position(POSITION_COMPONENT_COUNT)
        glVertexAttribPointer(aColorLocation, POSITION_COMPONENT_COUNT+ COLOR_COMPONENT_COUNT, GL_FLOAT, false, STRIDE, vertexData)

        glEnableVertexAttribArray(aColorLocation)
    }
}